﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;

namespace Code4WP7SDK
{
    public class WebClientService
    {
        public delegate void WebClientCompletedHandler(object sender, WebClientCompletedEventArgs e);
        public event WebClientCompletedHandler WebClientCompleted;

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <param name="url">http://luweibo.com</param>
        /// <param name="data">a=123&b=456</param>
        public void GetRequest(string url, string data)
        {
            WebClient webClient = new WebClient();
            webClient.Encoding = UTF8Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.UserAgent] = "Luweibo";
            webClient.UseDefaultCredentials = true;
            string getUrl = string.Concat(url, "?", data);
            webClient.DownloadStringCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        WebClientCompleted(s, new WebClientCompletedEventArgs(e.Result.ToString()));
                        GlobalLoading.Instance.IsBusy = false;
                    }
                    else
                    {
                        WebClientCompleted(s, new WebClientCompletedEventArgs(e.Error));
                    }
                };
            webClient.DownloadStringAsync(new Uri(getUrl, UriKind.Absolute));
            GlobalLoading.Instance.IsBusy = true;
        }
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="url">http://luweibo.com</param>
        /// <param name="data">a=123&b=456</param>
        public void PostRequest(string url, string data)
        {
            WebClient webClient = new WebClient();
            webClient.Encoding = UTF8Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded;charset=utf-8";

            webClient.UploadStringCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        WebClientCompleted(s, new WebClientCompletedEventArgs(e.Result.ToString()));
                    }
                    else
                    {
                        WebClientCompleted(s, new WebClientCompletedEventArgs(e.Error));
                    }
                };
            webClient.UploadStringAsync(new Uri(url, UriKind.Absolute), "POST", data);
        }
    }
}
